package svc

import (
	"github.com/zeromicro/go-zero/core/stores/redis"
	"im_sys/apps/im/immodels"
	"im_sys/apps/im/ws/ws_client"
	"im_sys/apps/task/mq/internal/config"
	"im_sys/pkg/constants"
	"net/http"
)

type ServiceContext struct {
	config.Config

	WsClient ws_client.Client
	*redis.Redis
	immodels.ChatLogModel
}

func NewServiceContext(c config.Config) *ServiceContext {
	svcCtx := &ServiceContext{
		Config: c,

		Redis:        redis.MustNewRedis(c.Redisx),
		ChatLogModel: immodels.NewChatLogModel(c.Mongo.Url, c.Mongo.DB, c.Mongo.Collection),
	}

	// 从redis中获取系统用户的token
	token, err := svcCtx.GetSystemToken()
	if err != nil {
		panic(err)
	}
	// 将token放入http头部，使得websocket client可以解析得到
	header := http.Header{}
	header.Set("Authorization", token)
	// 创建一个websocket客户端，用于与websocket服务端通信，服务端会查找接收者的websocket连接并发送消息
	svcCtx.WsClient = ws_client.NewClient(c.Websocket.Host, ws_client.WithServerHeader(header))

	return svcCtx
}

func (svc *ServiceContext) GetSystemToken() (string, error) {
	return svc.Redis.Get(constants.RedisSystemRootToken)
}
